package test

import (
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"study/testproject/source/bean"
	"study/testproject/source/service"
	"study/testproject/source/util"
	"study/testproject/source/util/httpSession"
)

//跳转到首页
func WebMsg(rw http.ResponseWriter, r *http.Request) {
	sess := httpSession.GetSession(rw, r)
	sessionval := sess.Get(util.USER_SESSION_KEY)
	if sessionval == nil { //未登录 查询数据
		tp, err := template.ParseFiles(util.HTML_PATH_ROOT + "login.html")
		if err != nil {
			fmt.Println(err)
			return
		}
		tp.Execute(rw, nil)
	} else {
		tp, err := template.ParseFiles(util.HTML_PATH_ROOT + "webmsg.html")
		if err != nil {
			fmt.Println(err)
			return
		}
		user, _ := sessionval.(bean.Users)

		tp.Execute(rw, user)
	}
}

//用户登录
func UserLogin(rw http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		tp, err := template.ParseFiles(util.HTML_PATH_ROOT + "login.html")
		if err != nil {
			fmt.Println(err)
			return
		}
		tp.Execute(rw, nil)
	} else {
		r.ParseForm()
		sess := httpSession.GetSession(rw, r)
		var uname string = r.Form.Get("uname")
		var upass string = r.Form.Get("upass")
		user, r := service.UserLogin(uname, upass)
		if r == 1 { //登录成功
			sess.Set(util.USER_SESSION_KEY, user)
			fmt.Fprint(rw, "1") //登录成功
			return
		}
		fmt.Fprint(rw, "0") //登录失败
	}
}
func InitMessage(rw http.ResponseWriter, r *http.Request) {
	sess := httpSession.GetSession(rw, r)
	sessionval := sess.Get(util.USER_SESSION_KEY)
	if sessionval != nil { //登录 查询数据
		user, ok := sessionval.(bean.Users)
		if ok {
			r.ParseForm()
			receiveuid := r.Form.Get("receiveuid")
			json := service.InitMessage(user.Uid, receiveuid)
			fmt.Fprint(rw, json)
		}
	} else {
		fmt.Fprint(rw, "-1")
	}
}

func GetUser(rw http.ResponseWriter, r *http.Request) {
	sess := httpSession.GetSession(rw, r)
	sessionval := sess.Get(util.USER_SESSION_KEY)
	if sessionval == nil {
		fmt.Fprint(rw, "-1")
	} else {
		user, ok := sessionval.(bean.Users)
		if ok {
			json := service.GetUser(user.Uid)
			fmt.Fprint(rw, json)
			return
		}
		fmt.Fprint(rw, "0")
	}
}

//输出json
func OutPutJson(rw http.ResponseWriter, data interface{}) {
	b, err := json.Marshal(data)
	if err != nil {
		rw.Write(b)
		return
	}
	rw.Write(b)
}
